#!/usr/bin/env python3
# Copyright (c) 2019-2020 Windy Albert

import hashlib
import binascii
import ecdsa
import os
import base58check

from keyTree import *




def base32_rfc4686_encode(src):
    str_map = "abcdefghijklmnopqrstuvwxyz234567"
    dst = []
    src_len = 0

    if len(src) == 0:
        return ''

    while len(src):
        src_len = len(src)
        next_byte = [0] * 8

        if src_len > 4:
            next_byte[7] = src[4] & 0x1f
            next_byte[6] = src[4] >> 5

        if src_len > 3:
            next_byte[6] = next_byte[6] | (src[3] << 3) & 0x1f
            next_byte[5] = (src[3] >> 2) & 0x1f
            next_byte[4] = src[3] >> 7

        if src_len > 2:
            next_byte[4] = next_byte[4] | (src[2] << 1) & 0x1f
            next_byte[3] = (src[2] >> 4) & 0x1f

        if src_len > 1:
            next_byte[3] = next_byte[3] | (src[1] << 4) & 0x1f
            next_byte[2] = (src[1] >> 1) & 0x1f
            next_byte[1] = (src[1] >> 6) & 0x1f

        if src_len > 0:
            next_byte[1] = next_byte[1] | (src[0] << 2) & 0x1f
            next_byte[0] = src[0] >> 3

        for nb in next_byte:
            dst.append(str_map[nb])

        src = src[5:]

    if src_len < 5:
        dst[-1] = '='
    if src_len < 4:
        dst[-2] = '='
        dst[-3] = '='
    if src_len < 3:
        dst[-4] = '='
    if src_len < 2:
        dst[-5] = '='
        dst[-6] = '='

    return ''.join(dst)



class addrFIL():
    def __init__(self, obj):
        self.obj = obj

    def getWallet(self,path):
        xprv = keyTree().getChildpriKey(self.obj,path)
        xprv_hex = base58check.b58decode(xprv["xprv"])
        prikey_hex = xprv_hex[46:78].hex()
        
        ## to Base64 format...
        path = self.obj["path"] + "/" + path
        wif = str(base64.b64encode(bytes.fromhex(prikey_hex)),'utf-8')
        pubkey = self.getPubkey(wif)
        addr = self.getAddr( pubkey )
        return {"path":path,"wif":wif,"addr":addr}

    def getPubkey(self,wif):
        prikey = base64.b64decode(wif)

        sk = ecdsa.SigningKey.from_string( prikey, curve=ecdsa.SECP256k1)    
        vk = sk.get_verifying_key() #this is your verification key (public key)
        public_key = vk.to_string("compressed").hex()
        return public_key

    def getAddr(self,pubkey):
        vk = ecdsa.VerifyingKey.from_string( bytes.fromhex(pubkey), curve=ecdsa.SECP256k1)
        public_key = vk.to_string("uncompressed")
        
        addr = hashlib.blake2b(digest_size=20)
        addr.update(bytes.fromhex(public_key.hex()))

        checksum = hashlib.blake2b(digest_size=4)
        checksum.update(bytes.fromhex("01"+addr.hexdigest()))
        
        result = base32_rfc4686_encode(bytes.fromhex(addr.hexdigest()+checksum.hexdigest()))

        return "f1" + result[:-1] #去掉最后的 “=” 

def main():
    # f1nbjjbuaeqqjxoiy263abatzgeohgclo5hchxjla
    # {"Type":"secp256k1","PrivateKey":"IVgmwJeEmWEDLbtqZVbE9AScCFMZJtfFDjWE8AZkWZs="}
    xprv = "xprv9zYiLCnTFKX1cBopDmmc2QjsJwSEjmqLYxr3aaDmQu35peWowGgEGiGBQSdpBLD9BsMYC8mmQ4XuUFUyiJxC4ikZ2UvUxSgQmAxRhu1dL5Q"


if __name__ == '__main__':
    main()